<template>
  <div class="home" ref="home" :style="{'background-color':tpl_html.backgroundColor}">
    <item-group-top-nav class="itemGroupTopNav" ref="itemGroupTopNav" v-if="itemGroupNavData.type == 32" :tplItemData="itemGroupNavData.content" @child-itemGroup="parentItemGroup"></item-group-top-nav>
    <!-- 装修数据 -->
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      finished-text=""
      @load="onLoad">
      <diy-tpl v-if="itemGroupId==0" :tplData="tplData" :hasMargin="tpl_html.hasMargin" :tplId="tplId" :style="{'padding-top': itemGroupPadding}" :itemGroupPadding="itemGroupPadding"></diy-tpl>
      <section ref="goodList" :style="{'padding-top': itemGroupPadding}" v-else>
        <!-- 商品分组组件 -->
        <div v-for="(item, index) in tplDataItemGroup" :key="index">
          <item-group v-if="item.type =='GoodsGroup'" :tplItemData="item.content" :itemPic="itemPic" :itemGroupId="itemGroupId"></item-group>
        </div>
      </section>
    </van-list>

    <!-- 自定义活动弹框 -->
    <div v-if="resDetail.is_open_diyActive==1&&resDetail.diy_active_box_img" class="j-active-box" v-show="isShowActive">
      <div class="diy-active-box-shade"></div>
      <input type="hidden" name="diy_active_box_frequency" :value="resDetail.diy_active_box_frequency">
      <input type="hidden" name="diy_active_box_freInfo" :value="resDetail.diy_active_box_freInfo">
      <div class="diy-active-box">
        <p class="box-del" @click="boxDel">&times;</p>
        <a @click="openLink(resDetail.diy_active_box_link)">
          <div class="active-content">
            <img :src="resDetail.diy_active_box_img" alt="">
          </div>
        </a>
      </div>
    </div>
    <!-- top panel -->
    <!-- <div class="top-panel">
      <div class="apptip" id="j-quickFollow-autohide" v-if="wxTipVisible">
        <i class="icon-close j-appdown-close" @click="wxTipVisible = false">
        </i>
        <div class="apptip-logo clearfix">
          <img class="fl" :src="resDetail.referee_headImg">
          <div class="apptip-logo-con">
              <span v-if="resDetail.referee_nick" class="apptip-text fl">好友,{{resDetail.referee_nick}}推荐<br />关注公众号，享专属服务</span>
              <span v-else class="apptip-text fl single">关注公众号，享专属服务</span>
          </div>
          <a href="javascript:;" class="apptip-btn fr j-quickFollow" @click="handleClickOneAll">立即关注</a>
        </div>
      </div> -->

      <!-- 在app中打开 -->
      <!-- <div v-if="resDetail.is_shop_app">
        <div class="apptip" id="j-appdown-autohide" v-if="appTipVisible">
          <i class="icon-close j-appdown-close" @click="appTipVisible = false">
          </i>
          <div class="apptip-logo clearfix">
            <img class="fl" :src="resDetail.shop_avatar">
            <span class="apptip-text fl single">在APP中购买商品</span>
            <a class="apptip-btn fr" href="javascript:;" id="j-openUrlInApp" @click="showAppVisible = true">立即打开</a>
          </div>
        </div> -->

        <!-- 微信中的弹层 -->
        <!-- <section class="open-in-browser"></section>

        <div class="app-wrap" v-if="showAppVisible">
          <section id="popup-protocol">
            <a href="javascript:;" class="popup-protocol-close" @click="showAppVisible = false"></a>
            <a href="javascript:;" class="popup-protocol-btn j-openProtocol" @click="handleClickOpenApp">在APP中打开</a>
            <a :href="resDetail.app_down" class="popup-protocol-btn download">下载APP</a>
            <p class="popup-protocol-tip">如果您未下载APP，请先下载</p>
          </section>
          <section id="popup-protocol-overlay" @click="showAppVisible = false"></section>
        </div>

      </div>
    </div> -->

    <shop-code ref="shopCode"></shop-code>
    <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
    <!-- ST unpay order tip cpt -->
    <unpay-order-tip-cpt v-if="is_mobile_pay_remind == 1" ref="unpay-order-tip-cpt"></unpay-order-tip-cpt>
    <!-- ED unpay order tip cpt -->
      <div class="index-loading" v-if="isLoading">加载中...</div>

  </div>
</template>

<script>
import { getLat, getLng } from '@/utils/auth'
// TODO 群接龙待同步
import UnpayOrderTipCpt from '@/components/public/unpay-order-tip'
import diyTpl from './shopTpl/index'
import { getTokenByKey, newSetTokenByKey } from '@/utils/auth'
import { openPage } from '@/utils/utils'
import { reqPostShop, getNewDiyHtml, indexConfig, getIndexGroupNav, universalLink } from '@/api/shop/index'
import { isIOS, isAPP, isWeixinCient } from '@/utils/validate'
// import { getDzShareItemConfig } from '@/api/dz/dzApi'
import Store from '@/utils/store'
// 商品分组导航
import itemGroupTopNav from '@/components/diyTpl/decoration/itemGroupTopNav'
import { getGroup } from '@/api/item/item'
import itemGroup from '@/components/diyTpl/decoration/itemGroup'
import goodsList from '@/components/diyTpl/decoration/goodsList'
import Vue from 'vue'
import SmallLogin from '@/components/SmallLogin/smallLogin.vue'
import small from '@/smallapp/small'
import ShopCode from '@/components/ShopCode'
// import { wxSceneExchange } from '@/api/small/login'

export default Vue.extend({
  components: {
    diyTpl,
    ShopCode,
    SmallLogin,
    itemGroupTopNav,
    itemGroup,
    goodsList,
    UnpayOrderTipCpt
  },
  data() {
    return {
      height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
      is_mobile_pay_remind: 0,
      openInBrowser: false,
      showAppVisible: false,
      appTipVisible: false,
      wxTipVisible: true,
      resDetail: {},
      tpl_html: {},
      tplId: 0,
      tplData: [],
      loading: false,
      finished: false,
      error: false,
      p: 2,
      isShowActive: false,
      isSubscribeQrcode: {},
      firstLoading: true,
      is_shop_referee: false,
      referee_nick: '',
      referee_headImg: '',
      // 兔宝宝定制
      // tbbStatus: false, // 店铺状态
      // is_show: false, // 定制是否显示
      list: {}, // 接收数据
      // 商品分组导航装修数据
      itemGroupId: '',
      itemGroupNavData: {},
      tplDataItemGroup: [],
      itemPic: '',
      itemGroupPadding: '',
      is_display_original_price: '1',
      isLoading: false,
      activeBox: {
        status: 0,
        time: 0
      }
    }
  },
  beforeCreate() {
    document.title = ''
  },
  created() {
    this.init()
    this.$loadingWrap.show()
  },
  mounted() {
    // TODO 小程序分享
      wx.hideHomeButton && wx.hideHomeButton()
      window.addEventListener('wxload', query => {
        // console.log(query , 'shopIndex')
        small.HandleShareParams()
      })
      window.addEventListener('wxshow', () => {
        // console.log('onshow')
        if(!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
      })
      window.onShareAppMessage = () => {
        // console.log('222', this.resDetail.applet_jsapi_img, this.resDetail)
        let _title = ''
        if (this.resDetail.is_store_log == 1) {
          _title = this.resDetail.page_title || '店铺首页'
        } else {
          _title = this.resDetail.shop_title || '店铺首页'
        }
        // console.log('_title', _title)
        // 当页面被转发时会进入这个回调
        // 返回一个对象，作为小程序处理转发的参数，对象内容和小程序页面 onShareAppMessage 回调可返回对象内容基本一致，具体可参考官方文档：https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#onShareAppMessage-Object-object
        if (this.resDetail.applet_jsapi_img) {
          return {
            title: _title,
              miniprogramPath: `/pages/shopIndex/index?type=open&targeturl=${encodeURIComponent('/index')}&sid=${small.globalData.shopId}&pid=${small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'}`, // 当前页面，这里的 path 是页面 url，而不是小程序路由
              imageUrl: this.resDetail.applet_jsapi_img
          }
        } else {
          return {
            title: _title,
              miniprogramPath: `/pages/shopIndex/index?type=open&targeturl=${encodeURIComponent('/index')}&sid=${small.globalData.shopId}&pid=${small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'}`, // 当前页面，这里的 path 是页面 url，而不是小程序路由
          }
        }
      }
      window.onShareTimeline = () => {
        let _title = ''
        if (this.resDetail.is_store_log == 1) {
          _title = this.resDetail.page_title || '店铺首页'
        } else {
          _title = this.resDetail.shop_title || '店铺首页'
        }
          // 当页面被分享朋友圈时会进入这个回调
          // 返回一个对象，作为小程序处理分享朋友圈的参数，对象内容和小程序页面 onShareTimeline 回调可返回对象内容基本一致，具体可参考官方文档：https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#onShareTimeline
        if (this.resDetail.applet_jsapi_img) {
          return {
              title: _title,
              imageUrl: this.resDetail.applet_jsapi_img,
              miniprogramQuery: `type=open&targeturl=${encodeURIComponent('/index')}&sid=${small.globalData.shopId}&pid=${small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'}`, // 如果需要分享原始小程序页面路由参数，可传递此参数
          }
        } else {
          return {
              title: _title,
              miniprogramQuery: `type=open&targeturl=${encodeURIComponent('/index')}&sid=${small.globalData.shopId}&pid=${small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'}`, // 如果需要分享原始小程序页面路由参数，可传递此参数
          }
        }
      }

      window.$$subscribe('loginReload', reload => {
        if (reload) {
          this.init()
        }
      })
      // TODO 下拉刷新
      window.addEventListener('pullDownRefresh', () => {
        wx.stopPullDownRefresh()
        setTimeout(() => {
          this.init(true)
        },500)
      })

      // TODO 触底加载
      window.addEventListener('reachbottom', () => {
        // console.log('shopIndex reachbottom')
        this.onLoad()
      })
  },
  beforeDestroy() {
    window.$$unsubscribe('loginReload')
  },
  methods: {
    openLink(link) {
      openPage(link)
    },
    init(hideLoading) {
      // 供应商通用链接
      const supplierPrev = this.$route.query.supplierPrev
      if (supplierPrev == 1) {
        universalLink().then(res => {
          if (res.status == 1 && res.data.jump_url) {
            // window.location.href = res.data.jump_url
            window.location.replace(res.data.jump_url)
          }
        })
      }
      this.finished = false
      this.p = 2
      // 获取装修数据
      this.getNewDiyHtml(hideLoading)
      this.indexConfigFn()
    },
    // TODO htmlCache、isSubscribeQrcode和ShopApi/index接口请求合并
    indexConfigFn() {
      const _data = {
        'sid': this.$store.getters.sid || Store.fetchLocal('sid'),
        'pid': Store.fetchLocal('pid') || '',
        'is_scan': this.$route.query.is_scan == 1 ? '1' : undefined
      }
      indexConfig(_data).then(res => {
        const data = res.data
        if (res.status == 1) {
          // cache数据
          const info = res.data.info
          this.is_shop_referee = info.is_shop_referee
          if (info.is_shop_referee) {
            this.referee_nick = info.referee_nick
            this.referee_headImg = info.referee_headImg
          }

          // 关注数据
          const follow_type = data.follow_type // 关注方式
          const follow_is_must_follow = data.is_must_follow // 是否强制关注
          const follow_is_display_subscribe = data.is_display_subscribe // 为true不显示图标自动跳转或显示二维码
          const follow_subscribe_url = data.subscribe_url // 关注引导页面的链接
          const follow_has_auto_goto = data.hasAutoGoto // 当天是否已经自动跳转过
          const follow_is_side_widget = data.is_side_widget // 是否显示微信图标关注
          const is_open_follow = data.is_open_follow
          const isSubscribeQrcode = {
            follow_type: follow_type,
            follow_is_must_follow: follow_is_must_follow,
            follow_is_display_subscribe: follow_is_display_subscribe,
            follow_subscribe_url: follow_subscribe_url,
            follow_has_auto_goto: follow_has_auto_goto,
            follow_is_side_widget: follow_is_side_widget,
            is_open_follow: is_open_follow
          }
          // if (window.localStorage) {
          //   setLocalStorage("isSubscribeQrcode", isSubscribeQrcode)
          // }
          this.isSubscribeQrcode = isSubscribeQrcode
          this.fnSubscribeQrcode(isSubscribeQrcode)
          this.is_mobile_pay_remind = data.is_mobile_pay_remind

          // 店铺首页数据
          let _title = ''
          if (data.index.is_store_log == 1) {
            _title = data.index.page_title || '店铺首页'
          } else {
            _title = data.index.shop_title || '店铺首页'
          }
            wx.setNavigationBarTitle({
              title: _title
            })
          this.resDetail = data.index
          this.referee_nick = this.resDetail.referee_nick
          this.referee_headImg = this.resDetail.referee_headImg
          this.tpl_html = this.resDetail.tpl_html
          // 首页弹窗
          if (this.resDetail.is_open_diyActive == 1 && this.resDetail.diy_active_box_img) {
            const status = this.resDetail.diy_active_box_frequency
            const time = this.resDetail.diy_active_box_freInfo
            this.activeBox.status = status
            this.activeBox.time = time
            if (status == 1) {
              this.isShowActive = true
            } else {
              if (getTokenByKey('Browse') == 'idea') {
                this.isShowActive = false
              } else {
                this.isShowActive = true
              }
            }
          }
          // 首页下载app提示
          // 判断是否显示打开app弹层
          if (isAPP()) {
            this.appTipVisible = false
          } else {
            this.appTipVisible = true
          }
          // 定时关闭app提醒
          if (data.show_app_time > 0) {
            setTimeout(() => {
              this.appTipVisible = false
            }, data.show_app_time)
          }
          // 分享数据处理
          // this.handleShare(res.data)
        }
      })
    },
    // 首页浮层展示
    fnSubscribeQrcode(obj) {
      // 判断是否显示微信关注图标
      if (obj.follow_is_display_subscribe == 1 && obj.follow_is_side_widget == 0) {
        // $(".quickFollow").show()
      } else {
        // $(".quickFollow").hide()
      }
      if (obj.is_open_follow != 1) return
      // 开启自动跳转，并且关注方式是显示公众号二维码
      if (obj.follow_is_display_subscribe == 0 && obj.follow_has_auto_goto != 1 && obj.follow_type == 1) {
        this.$refs.shopCode.dialogVisible = true
        // 强制关注打开的话，公众号二维码不能隐藏
        if (obj.follow_is_must_follow == 1) {
          this.qrcodeLock = true
        }
      }
    },
    // 一键关注
    handleClickOneAll() {
      const obj = this.isSubscribeQrcode
      if (obj.follow_type == 0) {
        window.location.href = obj.follow_subscribe_url
      } else if (obj.follow_type == 1) {
        this.$refs.shopCode.dialogVisible = true
      }
    },
    // 打开APP
    handleClickOpenApp() {
      if (this.qrcodeLock) return false
      const global_openUrlInApp_appUrl = this.resDetail.link_wfx_app // app协议及参数
      if (isIOS()) {
        window.location.href = global_openUrlInApp_appUrl
      } else {
        var iframe = document.createElement('iframe')
        document.body.appendChild(iframe)
        iframe.style.display = 'none'
        iframe.src = global_openUrlInApp_appUrl
      }
    },
    // 关闭弹框
    boxDel() {
      this.isShowActive = false
      this.setActiveBoxToken(this.activeBox.status, this.activeBox.time)
    },
    // 设置弹窗token
    setActiveBoxToken(status, time) {
      if (status != 1) {
        let _time = ''
        if (status == 0) {
          _time = 24
        } else if (status == 2 && time > 0) {
          _time = time
        }
        newSetTokenByKey('Browse', 'idea', _time, '/')
      }
    },

    // 首页装修组件数据
    getNewDiyHtml(hideLoading) {
      const tid = this.$route.query.tid
      const noHtmlCache = this.$route.query.noHtmlCache
      const param = {}
      param.latitude = getLat()
      param.longitude = getLng()
      if (tid) {
        param.tid = tid
        param.noHtmlCache = noHtmlCache
      }
      // param.test = 1
      if(!hideLoading){
        this.$loadingWrap.show()
      }
      this.$loadingWrap.show()
      getNewDiyHtml(param).then(res => {
        // TODO 获取到数据以后触发layout获取相关数据
        this.$loadingWrap.close()
        this.$Bus.$emit('diyRequestFinished', res)
        if (res.status == 1) {
          const data = res.data
          this.is_display_original_price = data.is_display_original_price
          this.tplData = data._diyHtml
          this.firstLoading = false
          this.tplId = data.homepage_tpl_id
          if (this.tplData.length < 10) {
            this.finished = true
          }
          // TODO小程序如果第一页加载没有满屏 则继续加载
            if (!this.finished) {
              this.$nextTick(() => {
                document.querySelector('.home').$$getBoundingClientRect().then(res=>{
                  if (res.height*1 < this.height*1) {
                    this.onLoad()
                  }
                })
              })
            }
          // 是否加载请求商品分组导航
          if (data.is_show_group_nav == 1) {
            this.getIndexGroupNav()
          }
        }
      })
    },

    // 首页装修组件加载更多
    onLoad() {
      if (this.finished) return false
      if (this.firstLoading) {
        this.loading = false
        return
      }
      const data = {
        p: this.p,
        latitude: getLat(),
        longitude: getLng()
      }
        this.isLoading = true
      getNewDiyHtml(data).then(res => {
          this.isLoading = false
        if (res.status == 1) {
          this.loading = false
          const data = res.data
          this.is_display_original_price = data.is_display_original_price
          this.tplData = this.tplData.concat(data._diyHtml)
          this.p++
          if (data._diyHtml.length < 10) {
            this.finished = true
          }
        }
      }).catch(() => {
        this.error = true
      })
    },

    // 商品分组导航
    // 滑动置顶
    getScrollTop() {
      // TODO 小程序滚动到顶部
        wx.pageScrollTo({
          scrollTop: 0
        })

    },
    parentItemGroup(groupId) {
      this.itemGroupId = groupId
      this.getGroupFun()
    },
    getGroupFun() {
      this.$loadingWrap.show()
      const data = {
        id: this.itemGroupId
      }
      getGroup(data).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const oDiyHtml = res.data._diyHtml
          document.title = res.data.page_title
          oDiyHtml.forEach(element => {
            if (element.type == 'GoodsGroup') {
              element.content.show_group_search = false
            }
          })
          this.tplDataItemGroup = oDiyHtml
          this.itemPic = res.data.itemPic
          this.is_display_original_price = res.data.is_display_original_price
          this.getScrollTop()
        }
      })
    },
    getIndexGroupNav() {
      this.$loadingWrap.show()
      getIndexGroupNav().then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          res.data.content.dataset.unshift({
            groupId: '0',
            showtitle: '首页'
          })
          this.itemGroupNavData = res.data
          setTimeout(() => {
              document.querySelector('.itemGroupTopNav').$$getBoundingClientRect().then(res => {
                this.itemGroupPadding = res.height + 'px'
              })
          }, 1000)
        }
      })
    },
  }
})
</script>

<style lang="scss">
.home {
  box-sizing: border-box;
  .j-active-box{
    .diy-active-box-shade{
      display: block;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,.4);
      z-index: 9997;
    }
    .diy-active-box{
      width: 70%;
      height: auto;
      position: fixed;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      z-index: 9998;
      .box-del{
        position: absolute;
        bottom: -80px;
        left: 50%;
        width: 50px;
        height: 50px;
        color: #fff;
        font-size: 50px;
        line-height: 44px;
        text-align: center;
        transform: translateX(-26px);
        font-family: sans-serif,"Helvetica Neue",Helvetica,STHeiTi;
        z-index: 9999;
        border-radius: 50%;
        border: 1px solid #fff;
      }
      >a{
        display: block;
        .active-content{
          width: 100%;
          height: 100%;
          overflow: hidden;
          img {
            width: 100%;
            max-height: 70%;
          }
        }
      }
    }
  }
  .top-panel {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1111;
    background: rgba(0,0,0,.1);
    .apptip {
      position: relative;
      height: 100px;
      background: rgba(0, 0, 0, .7);
      margin-bottom: 2px;
      .icon-close {
        display:block;
        position: absolute;
        top: 0;
        left:0;
        width:60px;
        height:60px;
        background:url("https://img.wifenxiao.com/h5-wfx/images/icon_close.png") no-repeat;
        background-size:100% 100%;
        /* width: 60px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        .icon{
          color: #fff;
          font-size: 26px;
        } */
      }
      .apptip-logo {
        margin: 0 10px 0 60px;
        img {
          max-width: 72px;
          max-height: 72px;
          margin-top: 14px;
        }
      }
      .apptip-text {
        display: block;
        width: 63%;
        padding: 0;
        font-size: 28px;
        color: #fff;
        line-height: 100px;
        height: 100px;
        overflow: hidden;
      }
      .apptip-text.single {
        /*line-height: 76px;*/
      }
      .apptip-btn {
        margin-top: 24px;
        height: 40px;
        line-height: 40px;
        padding: 6px 12px;
        color: #333;
        border-radius: 6px;
        background: -webkit-linear-gradient(top, #d5d5d5, #f0f0f0);
        background: -moz-linear-gradient(top, #d5d5d5, #f0f0f0);
        background: -o-linear-gradient(top, #d5d5d5, #f0f0f0);
        background: linear-gradient(top, #d5d5d5, #f0f0f0);
      }
      .apptip-btn.btn-follow {
        margin: 0;
      }
    }
  }
  .app-wrap{
    #popup-protocol {
      position: fixed;
      width: 80%;
      padding: 70px 30px;
      top: 50%;
      left: 50%;
      background: #fff;
      transform: translate(-50%, -50%);
      z-index: 9999;
      border-radius: 10px;
      .popup-protocol-close {
        display: block;
        position: absolute;
        right: -20px;
        top: -16px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: url(https://img.wifenxiao.com/h5-wfx/images/shop/index/popup-protocol-close.png) center no-repeat #373B3C;
        background-size: 44px auto;
      }
      .popup-protocol-btn {
        display: block;
        width: 80%;
        margin: 0 auto 40px;
        text-align: center;
        height: 80px;
        line-height: 80px;
        background-color: #5cb85c;
        border: 1px solid #4cae4c;
        color: #fff;
        font-size: 40px;
        border-radius: 10px;
        &.download {
          background-color: #f0ad4e;
          border: 2px solid #eea236;
          margin-bottom: 20px;
        }
      }
      .popup-protocol-tip {
        font-size: 28px;
        color: #565656;
        width: 80%;
        margin: 0 auto;
        text-align: center;
      }
    }

    #popup-protocol-overlay {
      position: fixed;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.6);
      z-index: 999;
    }
  }
  .index-loading {
    text-align: center;
    color: #999;
    line-height: 80px;
  }
}
</style>
